<template>
  <div>
    <!-- 搜索过滤区域 -->
    <el-form :model="searchForm" ref="searchFormRef" label-width="100px" class="search-filter">
      <el-row>
        <el-col :span="9">
          <el-form-item label="ID">
            <el-input v-model="searchForm.userId" placeholder="请输入ID" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="用户类型">
            <el-select v-model="searchForm.userType">
              <el-option label="全部" value="all" />
              <el-option label="用户" value="user" />
              <el-option label="商家" value="merchant" />
              <el-option label="骑手" value="rider" />
              <el-option label="站点" value="station" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户昵称">
            <el-input v-model="searchForm.nickname" placeholder="请输入用户昵称或名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="手机号码">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="时间范围">
            <el-select v-model="searchForm.time">
              <el-option label="近三个月" value="1" />
              <el-option label="今年内" value="2" />
              <el-option label="2024" value="3" />
              <el-option label="2023" value="4" />
              <el-option label="2022" value="5" />
              <el-option label="2022年之前" value="6" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交易状态">
            <el-select v-model="searchForm.transactionStatus">
              <el-option label="全部" value="all" />
              <el-option label="充值中" value="inProgress" />
              <el-option label="充值成功" value="success" />
              <el-option label="充值失败" value="failed" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item>
            <el-button type="success" @click="search">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item>
            <el-button type="info" @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 账户列表区域 -->
    <el-table :data="accountList" style="width: 100%; margin-top: 10px" stripe>
      <el-table-column label="ID" width="80">
        <template #default="scope">
          <el-link @click="openPopup(scope.row)">{{ scope.row.id }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="userType" label="用户类型" width="100">
        <template #default="scope">
          <span v-if="scope.row.userType === 1">用户</span>
          <span v-if="scope.row.userType === 2">商家</span>
          <span v-if="scope.row.userType === 3">骑手</span>
          <span v-if="scope.row.userType === 4">站点</span>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="昵称名称" width="200">
        <template #default="scope">
          <span :class="scope.row.typeClass">{{ scope.row.userName }}</span>
          <br>
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="accountBalance" label="账户余额" width="100" :formatter="formatCurrency" />
      <el-table-column prop="availableBalance" label="可用余额" width="100" :formatter="formatCurrency" />
      <el-table-column prop="receivable" label="待收" width="100" :formatter="formatCurrency" />
      <el-table-column prop="frozen" label="冻结" width="100" :formatter="formatCurrency" />
      <el-table-column prop="createTime" label="创建时间" width="140" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <span v-if="scope.row.status === 1">正常</span>
          <span v-if="scope.row.status === 2">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              ...
              <el-icon><caret-bottom /></el-icon>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click="handleFreeze(scope.row)">冻结账户</el-dropdown-item>
              <el-dropdown-item @click="handleUnfreeze(scope.row)">解冻账户</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination"
    />
    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="用户详情">
      <template #default>
        <div>
          <span>当前 ID: {{ currentId }}</span>
          <div style="margin-top: 20px;">
            <div style="display: flex; align-items: center;">
              <img
                :src="userInfo.newInformation || '头像图片路径'"
                alt="用户头像"
                style="width: 80px; height: 80px; border-radius: 50%; margin-right: 20px;"
              />
              <div>
                <p>用户ID：{{ userInfo.id }}</p>
                <p>手机号码：{{ userInfo.phone }}</p>
                <p>审核类型：{{ userInfo.auditType }}</p>
              </div>
            </div>
            <div style="display: flex; align-items: center; margin-top: 10px;">
              <div style="flex: 1;">
                <p>序列号：{{ userInfo.serialNumber }}</p>
                <p>用户ID（uid）：{{ userInfo.uid }}</p>
              </div>
              <div style="flex: 1; text-align: right;">
                <el-button v-if="userInfo.status === '2'" @click="lockUser(userInfo.id)">锁定用户</el-button>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <p>状态：{{ userInfo.status }}</p>
              <p>状态处理人：{{ userInfo.statusPerson }}</p>
            </div>
            <div style="margin-top: 20px;">
              <h4>基本信息</h4>
              <p>昵称：{{ userInfo.uname }}</p>
              <p>手机号码：{{ userInfo.phone }}</p>
              <p>提交时间：{{ userInfo.submitTime }}</p>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 商家弹窗 -->
    <el-dialog :visible.sync="dialogVisible2" title="商家详情">
      <template #default>
        <div>
          <span>当前 ID: {{ currentId }}</span>
          <div style="margin-top: 20px;">
            <div style="display: flex; align-items: center;">
              <img
                :src="merchantInfo.images ? merchantInfo.images.split(',')[0] : '头像图片路径'"
                alt="商家头像"
                style="width: 80px; height: 80px; border-radius: 50%; margin-right: 20px;"
              />
              <div>
                <p>用户名：{{ merchantInfo.username }}</p>
                <p>手机号码：{{ merchantInfo.phone }}</p>
                <p>营业执照有效期：{{ formatDate(merchantInfo.validity) }}</p>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <p>备注：{{ merchantInfo.remark }}</p>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="dialogVisible2 = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, getList, getOne, getOneStore } from '@/api/accounts';

export default {
  data() {
    return {
      searchForm: {
        userId: '',
        userType: '',
        nickname: '',
        phone: '',
        time: '',
        status: ''
      },
      searchFormRef: null,
      accountList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogVisible2: false,
      currentId: null,
      userInfo: {},
      merchantInfo: {}
    };
  },
  created() {
    this.search();
  },
  methods: {
    search() {
      const params = {
       ...this.searchForm,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      getList(params).then(res => {
        this.accountList = res.data.records;
        this.total = res.data.total;
      }).catch(error => {
        ElMessage.error('查询失败，请稍后重试');
        console.error('查询账户列表失败:', error);
      });
    },
    reset() {
      this.searchForm = {
        userId: '',
        userType: '',
        nickname: '',
        phone: '',
        time: '',
        accountStatus: ''
      };
      this.currentPage = 1;
      this.search();
    },
    formatCurrency(row, column, cellValue) {
      return `¥${cellValue}`;
    },
    freezeAccount(account) {
      // 实际应调用后端接口
      ElMessage.success('冻结账户成功');
      this.search();
    },
    unfreezeAccount(account) {
      // 实际应调用后端接口
      ElMessage.success('解冻账户成功');
      this.search();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    openPopup(row) {
      console.log('251行');
      console.log(row);
      if (row.userType === 1) {
        this.dialogVisible = true;
        this.currentId = row.id;
        getOne(row.id).then(res => {
          this.userInfo = res.data;
        }).catch(error => {
          ElMessage.error('查询失败，请稍后重试');
          console.error('查询账户详情失败:', error);
        });
      } else if (row.userType === 2) {
        this.dialogVisible2 = true;
        this.currentId = row.id;
        getOneStore(row.id).then(res => {
          this.merchantInfo = res.data;
        }).catch(error => {
          ElMessage.error('查询失败，请稍后重试');
          console.error('查询账户详情失败:', error);
        });
      }
    },
    handleFreeze(row) {
      // 冻结账户逻辑，比如调用后端接口
      console.log('执行冻结账户操作', row);
    },
    handleUnfreeze(row) {
      // 解冻账户逻辑，比如调用后端接口
      console.log('执行解冻账户操作', row);
    },
    lockUser(userId) {
      // 锁定用户逻辑，比如调用后端接口
      console.log('执行锁定用户操作', userId);
    },
    formatDate(dateStr) {
      if (dateStr) {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      return '';
    }
  }
};
</script>

<style scoped>
.search-filter {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>